package mn.slide.ubjam.parser;

import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import mn.slide.ubjam.model.Grade;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class GradeParser
{
	/**
	 * @author Slide LTD [Б.Отгонбаяр]
	 * @since [2012-2-20]
	 * 
	 *        Замын grade-уудыг Сервер дэх XML-с parse
	 *        хийх
	 */

	// RoadStatus-уудыг хийх жагсаалт
	public static ArrayList<Grade>	gradeList	= new ArrayList<Grade>();	;
	public static final String		LOG_TAG		= "RoadStatusParser";

	/**
	 * 
	 * Статус - уудыг parse хийж жагсаалтад хийх
	 * 
	 * @param is
	 *            - Татсан XML файлын InputStream
	 */
	public static ArrayList<Grade> parser( InputStream is )
	{

		gradeList = new ArrayList<Grade>();
		try
		{
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParser = factory.newSAXParser();

			DefaultHandler handler = new DefaultHandler()
			{
				int	grade;
				int	speed;

				public void startElement( String uri , String localName , String qName , Attributes attributes ) throws SAXException
				{

					if (qName.equalsIgnoreCase("link"))
					{
						grade = Integer.parseInt(attributes.getValue("trafficGrade"));
						speed = Integer.parseInt(attributes.getValue("speed"));
						gradeList.add(new Grade(speed, grade));
						// Log.v(LOG_TAG, "grade: [" + grade + "]");
						// Log.v(LOG_TAG, "speed: [" + speed + "]");
					}
				}

				public void endElement( String uri , String localName , String qName ) throws SAXException
				{
					if (qName.equalsIgnoreCase("roadInfo"))
					{
						Log.v("Parser", "PARSE ХИЙЖ ДУУСАВ!!! Нийт: [" + gradeList.size() + "] ширхэг замын СТАТУС (grade) байна.");
					}
				}
			};
			saxParser.parse(is, handler);

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return gradeList;
	}
}
